package cn.stronglink.assetmanage.business.check.assetlist;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.detail.CheckDetailActivity;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.MessageEvent;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.listener.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.LogUtil;
import cn.stronglink.assetmanage.utils.PrefUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.CheckDataUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class UncheckAssetFragment extends Fragment implements onRecyclerListener,
        UnCheckAssetAdapter.OnItemCheckedChangedListener, UnCheckAssetAdapter.OnItemScanRfidListener,
        IScanerListener {
    private String orderNo, location;
    Unbinder mUnbinder;
    @BindView(R.id.rv_uncheck_asset_list)
    RecyclerView rvUncheckAssetList;
    @BindView(R.id.btn_check_save_order)
    Button btn_check_save_order;
    @BindView(R.id.btn_save_asset)
    Button btn_save_asset;
    @BindView(R.id.cb_check)
    CheckBox cb_check;
    private UnCheckAssetAdapter mAdapter;
    private List<Asset> mAssetList = new ArrayList<>();
    private List<Asset> checkedAssetList = new ArrayList<>();
    private Check mCheck;
    private AssetListActivity mActivity;
    private TimerInfraraedScaner scaner;
    private static final String TAG = "UncheckAssetFragment";

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (AssetListActivity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_uncheck_asset, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (mActivity != null) {
            this.scaner = new TimerInfraraedScaner(mActivity);
            this.scaner.setScanerListener(this);
        }
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAdapter = new UnCheckAssetAdapter(mActivity);
        mAdapter.setListener(this);
        mAdapter.setOnItemCheckedChangedListener(this);
        mAdapter.setOnItemScanRfidListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity,
                LinearLayoutManager.VERTICAL, false);
        rvUncheckAssetList.setLayoutManager(layoutManager);
        rvUncheckAssetList.setAdapter(mAdapter);
        setOrderInfo(AssetListActivity.orderNo, mActivity.getString(R.string.all_location));
        //全选和取消全选
        checkBoxChanged();
    }


    private void checkBoxChanged() {
        cb_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setAllCheck(isChecked);
            }
        });
    }

    private void setAllCheck(boolean isChecked) {
        if (mAdapter != null) {
            mAdapter.setAllCheck(isChecked);
        }
        checkedAssetList.clear();
        checkedAssetList = new ArrayList<>();
        if (isChecked) {
            //全选
            checkedAssetList.addAll(mAssetList);
        }
    }


    public void setOrderInfo(final String orderNo, final String location) {
        this.orderNo = orderNo;
        this.location = location;
        mCheck = CheckDataUtil.getCheckByOrderNo(orderNo);
        if (mCheck != null && mCheck.getStatus() == Constants.STATUS_FOUR) {
            //入库单不再显示“表单入库”按钮
            btn_check_save_order.setVisibility(View.INVISIBLE);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                mAssetList = CheckDataUtil.getUnCheckAssetByOrderNoAndLocation(orderNo, location);
                if (mActivity != null) {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mAdapter != null) {
                                mAdapter.notifyDataChanged(mAssetList);
                            }
                        }
                    });
                }
            }
        }).start();


    }

    @OnClick({R.id.btn_check_save_order, R.id.btn_save_asset})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_check_save_order:
                saveCheckData();
                break;
            case R.id.btn_save_asset:
                saveAssetData();
                break;
            default:
                break;
        }
    }

    public void saveCheckData() {
        //将check入库
        mCheck.setExecutor(User.getInstance().getName());
        String time = CheckDataUtil.updateTime();
        mCheck.setUpdateTime(time);
        mCheck.setExecutionTime(time);
        String userId = User.getInstance().getId_();
        if (userId != null && !"".equals(userId)) {
            mCheck.setUpdateBy(Long.valueOf(userId));
        }
        CheckDataUtil.saveCheckedOrder(mCheck);
        ToastUtil.toastShort(R.string.success);
        //表单入库后，返回本页面销毁
        if (mActivity != null) {
            mActivity.finish();
        }
    }


    public void saveAssetData() {
        if (checkedAssetList != null && checkedAssetList.size() != 0) {
            //入库资产数据
            CheckDataUtil.saveAssetList(checkedAssetList);
            String time = CheckDataUtil.updateTime();
            mCheck.setUpdateTime(time);
            mCheck.setExecutionTime(time);
            CheckDataUtil.updateCheck(mCheck);
            ToastUtil.toastShort(R.string.success);
            //表单入库后，刷新本页面
            if (mActivity != null) {
                mActivity.onResume();
                checkedAssetList.clear();
            }
        } else {
            ToastUtil.toastShort("请选择入库资产");
        }
    }


    @Override
    public void onItemClicked(View v, int postion) {
        // 跳转到详情页
        if (mActivity != null) {
            cb_check.setChecked(false);
            setAllCheck(false);
            Intent intent = new Intent(mActivity, CheckDetailActivity.class);
            intent.putExtra(Constants.CHECK_IN_DETAIL_NO, mAssetList.get(postion).getAsset_id_key());
            startActivity(intent);
        }

    }

    @Override
    public void onItemCheckedChanged(CompoundButton buttonView, boolean isChecked, int position) {
        if (position == -1) {
            return;
        }
        if (isChecked) {
            //选择某个位置上的数据
            checkedAssetList.add(mAssetList.get(position));
        } else {
            //取消选择某个位置上的数据
            checkedAssetList.remove(mAssetList.get(position));
        }
    }

    Asset asset = null;

    @Override
    public void onItemScanRfid(View view, int position) {
        if (mAssetList != null && mAssetList.size() > 0) {
            asset = new Asset();
            asset = mAssetList.get(position);
            if (mActivity != null && scaner == null) {
                this.scaner = new TimerInfraraedScaner(mActivity);
                this.scaner.setScanerListener(this);
            }
            if (scaner != null) {
                scaner.playSingle();
            }
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (scaner != null) {
            scaner.stop();
            scaner.destory();
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateData(MessageEvent messageEvent) {
        if (messageEvent != null && Constants.FIFTLER_ASSET_DATA.equals(messageEvent.getType())) {
            String[] dataArr = (String[]) messageEvent.getMessage();
            String orderNo = dataArr[0];
            String roomName = dataArr[1];
            setOrderInfo(orderNo, roomName);
            cb_check.setChecked(false);
            setAllCheck(false);
        }
    }

    @Override
    public void onScaning(List<String> data) {
        String resultData = data.get(data.size() - 1).replace(" ", "");
        if (asset != null) {
            asset.setRfidNo(resultData);
            asset.setUpdateTime(CheckDataUtil.updateTime());
            mCheck.setUpdateTime(CheckDataUtil.updateTime());
            CheckDataUtil.saveAsset(asset);
            mAssetList = CheckDataUtil.getUnCheckAssetByOrderNoAndLocation(orderNo, location);
            mAdapter.notifyDataChanged(mAssetList);
        }
    }
}
